import {
	fetchDeleteVirtualRoom,
	fetchGetVirtualRoom,
	fetchLoadVirtualResource,
	fetchLoadVirtualRoomList,
} from '@/api/sysConfig/virtualRoomConfig'
import { IRoomConfigInfo, IVirtualRoomItem } from '@/api/sysConfig/virtualRoomConfig/interface'
import Alert, { confirmModal } from '@/components/Alert'
import Table from '@/components/Table'
import { Button, ColumnProps, Space, Tag } from '@kedacom/react-next'
import { useRequest } from 'ahooks'
import React, { useEffect, useState } from 'react'
import { StyledWrap } from './style'
import ConfigInfo from './ConfigInfo'
import { IVirtualRoomListItem } from './interface'
import { getOptionValue, transVirtualRoomItem, transVirtualRoomListItem } from './translator'
import { fetchStatus } from '@/api/global'
import DetailModal from './DetailModal'
import { defaultTpl, useVirtualRoomStore } from './store'
import shallow from 'zustand/shallow'
import VirtualRoomEdit from './VirtualRoomEdit'
import { useGlobalStore } from '@/store/global'
import { t } from 'i18next'
import { getSelfMediaAbilityVal } from '@/pages/create/createContent/blocks/meetingParams/store.media'

const pageSize = 20

export default function VirtualRoomConfig() {
	const [selectedRowIds, setSelectedRowIds] = useState<Array<string>>([])
	const [roomConfig, setRoomConfig] = useState<IRoomConfigInfo[]>([])
	const [data, setData] = useState<IVirtualRoomListItem[]>([])
	const [isAddShow, setIsAddShow] = useState<boolean>(false)
	const [isModalShow, setIsModalShow] = useState<boolean>(false)
	const [modalData, setModalData] = useState<IVirtualRoomItem | null>(null)
	const [pager, setPager] = useState({
		page: 1,
		size: pageSize,
		total: 1,
	})
	const { isEdit, update, initMeetingTypeList, initVrsList, changeMeetingType } = useVirtualRoomStore(
		(state) => ({
			isEdit: state.isEdit,
			update: state.update,
			initMeetingTypeList: state.initMeetingTypeList,
			initVrsList: state.initVrsList,
			changeMeetingType: state.changeMeetingType,
		}),
		shallow
	)

	const { user, serverInfo } = useGlobalStore(
		(state) => ({
			user: state.user,
			serverInfo: state.serverInfo,
		}),
		shallow
	)
	const initPermission = () => {
		update({
			//更新权限信息
			permission: {
				tradMix: serverInfo?.trad_mix || 0,
				portMix: serverInfo?.port_mix || 0,
				enableVRS: !!user?.enable_vrs,
				enableDCS: !!user?.enable_dcs,
				enableLive: !!user?.enable_live,
				enableVideo: !!user?.enable_video,
				enableQuantum: !!serverInfo?.enable_quantum,
				enablePortMedia: !!user?.enable_port_media,
				enableSfu: !!user?.enable_sfu,
				enableTrans: !!user?.enable_trans,
				enableHDMeeting: !!user?.enable_hd_meeting,
				certificate: !!serverInfo?.enable_sm4,
				integrated: !!serverInfo?.integrated,
				hasAuthenticationServer: !!serverInfo?.has_auth_server,
				sm1: !!serverInfo?.enable_sm1,
				'60fps': !!serverInfo?.enable60fps,
				'4K': !!serverInfo?.enable4k,
				h265: !!user?.enable_h265,
				has60FpsInH265: !!serverInfo?.enable60fps && !!user?.enable_h265 && !!!serverInfo?.jd2000,
			},
		})
	}

	useEffect(() => {
		if (!isEdit) {
			//初始化
			loadVirtualResource()
			loadVirtualRoomList(1)
			setSelectedRowIds([])
		}
	}, [isEdit])

	const { run: loadVirtualResource, loading: infoLoading } = useRequest(fetchLoadVirtualResource, {
		manual: true,
		onSuccess: (res) => {
			if (res.success) {
				let list = res.list
				if (list && list.length !== 0) {
					setRoomConfig(list)
					setIsAddShow(
						list.every((item) => {
							return item.config_count < item.total_count
						})
					)
				}
			} else {
				Alert(res.description ?? t('操作失败'))
			}
		},
	})

	const { run: loadVirtualRoomList } = useRequest(
		(pageIndex) => fetchLoadVirtualRoomList({ count: pager.size, start: (pageIndex - 1) * pager.size, order: 1 }),
		{
			manual: true,
			onSuccess: (res, [pageIndex]) => {
				if (res.success) {
					let arr = transVirtualRoomListItem(res.list)
					setData(arr)
					let total = res.total
					let maxPageNum = total === 0 ? 1 : Math.ceil(total / pager.size)
					if (maxPageNum < pageIndex) {
						setPager({ ...pager, page: maxPageNum, total })
						loadVirtualRoomList(maxPageNum)
					} else {
						setPager({ ...pager, page: pageIndex, total })
					}
				} else {
					Alert(res.description ?? t('操作失败'))
				}
			},
		}
	)

	const onPageChange = (pageIndex: number) => {
		loadVirtualRoomList(pageIndex)
	}

	const handleAdd = async () => {
		if (
			!roomConfig.every((item) => {
				return item.config_count < item.total_count
			})
		) {
			Alert(t('虚拟会议室总数已达到最大值，如有需要请申请更多资源'))
			return
		}
		initPermission()
		let defaultMeetingType = initMeetingTypeList() as 0 | 1 | 2
		let vrsId = (await initVrsList()) ?? ''
		update({
			isEdit: true,
			data: {
				...defaultTpl,
				vrsId,
			},
		})
		changeMeetingType(defaultMeetingType)
	}

	const handleEdit = () => {
		if (selectedRowIds.length !== 1) {
			Alert(t('请选择其中1条编辑'))
		} else {
			const checkedMeeting = data.find((item) => {
				return item.id === selectedRowIds[0]
			})
			if (checkedMeeting) {
				toEditPage(checkedMeeting.id, checkedMeeting.status === 'inUse')
			}
		}
	}

	const toEditPage = (id: string, inUse: boolean) => {
		if (inUse) {
			Alert(t('虚拟会议室正在使用中，无法修改。'))
		} else {
			fetchGetVirtualRoom(id).then((res) => {
				if (res.success) {
					let _data = transVirtualRoomItem(res)
					initPermission()
					initMeetingTypeList()
					initVrsList()
					let bitrateType =
						_data.meetingType === 2
							? _data.resolution === 12
								? 4
								: 6
							: getOptionValue({ ..._data, rate: _data.rate ?? 0 })
					update({
						isEdit: true,
						data: {
							..._data,
							_H265: _data.video === 6,
							_bitrateType: bitrateType,
							_selfMediaList: [],
							_selfMediaValue:
								bitrateType === 0 ? getSelfMediaAbilityVal(_data.resolution, _data.frame) : 0,
						},
					})
				} else {
					Alert(res.description ?? t('获取失败'))
				}
			})
		}
	}

	const handleDelete = () => {
		if (selectedRowIds.length <= 0) {
			Alert(t('请选择其中1条删除'))
		} else {
			fetchStatus(() => {
				confirmModal({
					msg: <div>{t('您确认要删除当前选中的全部虚拟会议室吗？')}</div>,
					onOk: () => {
						fetchDeleteVirtualRoom(selectedRowIds).then((res) => {
							if (res.success) {
								loadVirtualResource()
								if (data.length <= selectedRowIds.length) {
									loadVirtualRoomList(Math.max(pager.page - 1, 1))
								} else {
									loadVirtualRoomList(pager.page)
								}
								setSelectedRowIds([])
							} else {
								Alert(res.description ?? t('删除失败'))
							}
						})
					},
				})
			})
		}
	}

	const getDetail = (id: string) => {
		fetchGetVirtualRoom(id).then((res) => {
			if (res.success) {
				setIsModalShow(true)
				setModalData(res)
			} else {
				Alert(res.description ?? t('获取失败'))
			}
		})
	}

	const columns: ColumnProps<IVirtualRoomListItem>[] = [
		{ title: t('会议室名称'), dataKey: 'name' },
		{ title: t('会议室规模'), dataKey: 'type', width: 122 },
		{ title: t('虚拟会议室号码'), dataKey: 'e164', width: 136 },
		{ title: t('会议码率'), dataKey: 'rate', width: 186 },
		{
			title: t('专属'),
			dataKey: 'exclusive',
			width: 76,
			render: (rowData) => (rowData.exclusive === 'open' ? t('开启') : t('关闭')),
		},
		{ title: t('专属人员'), dataKey: 'exclusiveUser', width: 206 },
		{
			title: t('来宾会议室'),
			dataKey: 'publicMeeting',
			width: 75,
			render: (rowData) => (rowData.publicMeeting === 'open' ? t('开启') : t('关闭')),
		},
		{
			title: t('状态'),
			dataKey: 'status',
			width: 61,
			render: (rowData) => (rowData.status === 'inUse' ? t('使用中') : t('空闲')),
		},
		{
			title: t('操作'),
			dataKey: 'action',
			width: 61,
			render: (rowData) => {
				return (
					<Tag
						onClick={(e) => {
							e.stopPropagation()
							getDetail(rowData.id)
						}}
					>
						{t('详情')}
					</Tag>
				)
			},
		},
	]
	return (
		<>
			{!isEdit && (
				<StyledWrap className="virtual-room-list">
					{roomConfig.length === 0 && !infoLoading && (
						<div className="mask">
							<span>{t('尚未配置虚拟会议室，请联系管理员')}</span>
						</div>
					)}
					{roomConfig.length !== 0 && (
						<>
							<div className="room-config">
								{roomConfig?.map((item) => {
									return <ConfigInfo data={item} key={item.id} />
								})}
							</div>
							<div className="table-header">
								<span className="table-title">{t('虚拟会议室配置列表')}</span>
								<Space className="btns" space={3}>
									{isAddShow && (
										<Button className="add" onClick={handleAdd}>
											{t('添加')}
										</Button>
									)}
									<Button className="change" onClick={handleEdit}>
										{t('修改')}
									</Button>
									<Button className="delete" onClick={handleDelete}>
										{t('删除')}
									</Button>
								</Space>
							</div>
							<Table
								columns={columns}
								tableDataList={data}
								pager={pager}
								onPageChange={onPageChange}
								nodata={
									<div className="empty-msg">{t('目前无任何会议室信息，请您添加相应的会议室。')}</div>
								}
								selectedRowIds={selectedRowIds}
								onRowSelectAll={(e, selectedRowData, selectedRowIds: string[], nextSelected) => {
									setSelectedRowIds([...selectedRowIds])
								}}
								onRowClick={(e, rowData, id: string, nextSelected, index) => {
									if (nextSelected) {
										setSelectedRowIds([...selectedRowIds, id])
									} else {
										setSelectedRowIds(selectedRowIds.filter((item) => item !== id))
									}
								}}
								i18n={{ order: t('序号') }}
							/>
						</>
					)}
					<DetailModal
						isShow={isModalShow}
						setIsShow={setIsModalShow}
						orgData={modalData}
						handleEdit={toEditPage}
					/>
				</StyledWrap>
			)}
			{isEdit && <VirtualRoomEdit />}
		</>
	)
}
